package com.asm.handler;

import com.asm.message.GroupCreateRequestMessage;
import com.asm.message.GroupCreateResponseMessage;
import com.asm.server.session.Group;
import com.asm.server.session.GroupSession;
import com.asm.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;

@ChannelHandler.Sharable  //可共享，无其他类型消息
public class GroupCreatRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        //获取群的名称
        String groupName = msg.getGroupName();
        //获取群的成员
        Set<String> members = msg.getMembers();
        //获取群组管理器
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        //如果这个群名不存在才可以创建成功
        Group group = groupSession.createGroup(groupName, members);
        if(group==null){
            //发送成功消息
            ctx.writeAndFlush(new GroupCreateResponseMessage(true,groupName+"创建成功"));
            //发送拉群消息
            List<Channel> Channels = groupSession.getMembersChannel(groupName);//只有在线的才会返回channel
            for (Channel channel : Channels) {
               channel.writeAndFlush(new GroupCreateResponseMessage(true,"你已被拉入"+groupName));
            }



        }else {
            //发送失败消息
            ctx.writeAndFlush(new GroupCreateResponseMessage(false,groupName+"群名已经存在"));
        }
    }
}
